const F2 = require('../../../../component/ui/f2-canvas/lib/f2')
const api = require('../../../../wxapi/config.js')
Page({

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '影视行业大数据',
      path: '/pages/index/inedx/index',
    }
  },
  data: {
    stars: 0,
    poster: {
      mc: '-',
      pf: '-',
      lx: '-',
      bj: '-',
      dy: '-',
      zpr: '-',
      url: ''
    },
    roleInfoList: [],
    busiId: '',
    mc: '',
    sourceType: '',
    isRoleInfoloading: true,
    haibaoimg: 'https://cdn.xtde.cn/wxapp/xtde/haibao.png',
    touxiang: 'https://cdn.xtde.cn/wxapp/xtde/touxiang.jpg',
    themeOpts1: {
      lazyLoad: true
    },
    themeOpts2: {
      lazyLoad: true
    },
    themeItem1: {},
    themeItem2: {},
    hasthemeChartData: false,
    isthemeChartloading: true,
    ishistoryloading: true,
    historytableData: [],
    skeleton: [1, 2, 3],
    isActive: [
      { isActived: false },
      { isActived: false },
      { isActived: false },
      { isActived: false },
    ],
		weekpfopts: {
			lazyLoad: true
		},
		daypfopts: {
			lazyLoad: true
		},
		weekPfboxH: 500,
		istotalPfloading: true,
		isWeekPfloading: true,
		isDayPfloading: true,
		weekPfData: [],
		dayPfData: [],
		totalPfData: {},
		dateRange: {}
  },

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
    this.setData({
			sourceType: options.type,
			mc: options.name,
			busiId: options.id
    }) 
    this.getPoster(options.id)
    this.getRoleInfoList(options.id)
	},
  toggleActive: function (e) {
    var _this = this
    let i = e.target.dataset.item
    let isActived = 'isActive[' + i + '].isActived';
    _this.setData({ [isActived]: !this.data.isActive[i].isActived });
  },
  // 切换基础信息/制作公司/播出情况
  onChangeNav(event) {
    if (event.detail.index === 1 && this.data.historytableData.length === 0) {
      this.getHistory(this.data.mc)
      this.getThemeChart(this.data.mc)
		} else if (event.detail.index === 2 && this.data.weekPfData.length === 0) {
			this.getTotalPf(this.data.busiId)
			this.getWeekPfData(this.data.busiId)
			this.getDayPfData(this.data.busiId)
		}
  },
  toActorDetailPage(e) {
    wx.navigateTo({
      url: '/pages/search/search-detail/actor-detail/actor-detail?id=' + e.currentTarget.dataset.roleid
    })
  },
  getPoster(id) {
    api.getFilmPosterList({ busiId: id }).then((res) => { // 正式接口
      if (res.data.length !== 0) {
        this.setData({
          poster: res.data[0],
          stars: (parseFloat(res.data[0].pf) / 2).toFixed(1)
        })
      } else {
        this.setData({
          poster: {
            mc: this.data.mc,
            pf: '-',
            lx: '-',
            bj: '-',
            dy: '-',
            zpr: '-',
            url: ''
          }
        })
      }
    })
  },
  getRoleInfoList(filmId) {
    api.getFilmBaseInfo({ busiId: filmId }).then((res) => {
      if (res.data.length !== 0) {
        this.setData({
          roleInfoList: res.data,
          isRoleInfoloading: false
        })
      } else {
        this.setData({
          roleInfoList: [],
          isRoleInfoloading: false
        })
      }
    })
  },
  getHistory(mc) {
    let apiMap = { "1": "getMakeTeleplayHistoryList", "2": "getMakeFilmHistoryList" }
    api.getMakeFilmHistoryList({ mc: mc }).then((res) => {
      if (res.data.length !== 0) {
        this.setData({
          historytableData: res.data,
          ishistoryloading: false
        })
      } else {
        this.setData({
          historytableData: [],
          ishistoryloading: false
        })
      }
    })
  },
  // 获取题材占比
  getThemeChart(mc) {
    let apiMap = { "1": "getTeleplayGenresRateList", "2": "getFilmGenresRateList" }
    api.getFilmGenresRateList({ mc: mc }).then((res) => {
      if (res.data[0].plan.length !== 0 || res.data[0].release.length !== 0) {
        // console.log(res.data[0])
        if (res.data[0].plan.length !== 0) {
          this.setData({
            themeItem1: {
              name: res.data[0].plan[0].lx,
              total: parseInt(res.data[0].plan[0].total) * 100 + '%'
            },
            isthemeChartloading: false
          })
          var data1 = []
          for (let i in res.data[0].plan) {
            data1.push({
              name: res.data[0].plan[i].lx,
              total: parseInt(res.data[0].plan[i].total)
            })
          }
          this.pieSelectChart('compertheme1', data1, 0)
        }
        if (res.data[0].release.length !== 0) {
          this.setData({
            themeItem2: {
              name: res.data[0].release[0].lx,
              total: parseInt(res.data[0].release[0].total) * 100 + '%'
            },
            isthemeChartloading: false
          })
          var data2 = []
          for (let i in res.data[0].release) {
            data2.push({
              name: res.data[0].release[i].lx,
              total: parseInt(res.data[0].release[i].total)
            })
          }
          this.pieSelectChart('compertheme2', data2, 0)
        }
      } else {
        this.setData({
          themeItem1: '',
          themeItem2: '',
          hasthemeChartData: true,
          isthemeChartloading: false
        })
      }
    })

  },
  //环状图
  pieSelectChart(id, data, type) {
    this.chartComponent = this.selectComponent('#' + id);
    this.chartComponent.init((canvas, width, height) => {
      var chart = new F2.Chart({
        el: canvas,
        width,
        height
      });
      chart.source(data, {
        percent: {
          formatter: function formatter(val) {
            return val * 100 + '%';
          }
        }
      });
      // chart.legend({
      // 	position: 'bottom',
      // 	align: 'center'
      // });
      chart.legend(false)
      chart.tooltip(false)
      chart.coord('polar', {
        transposed: true,
        radius: 0.95,
        innerRadius: 0.8
      });
      chart.axis(false)
      chart
        .interval()
        .position('a*total')
        .color('name')
        .adjust('stack')
        .style({
          lineWidth: 1,
          stroke: '#fff',
          lineJoin: 'round',
          lineCap: 'round'
        });

      chart.interaction('pie-select', {
        cancelable: false, // 不允许取消选中
        animate: {
          duration: 300,
          easing: 'backOut'
        },
        defaultSelected: {
          name: data[0].name,
          total: data[0].total * 100 + '%'
        },
        onEnd: (ev) => {
          const { shape, data, shapeInfo, selected } = ev;
          if (shape) {
            if (selected) {
              if (type === 0) {
                this.setData({
                  themeItem1: {
                    name: data.name,
                    total: data.total * 100 + '%'
                  }
                })
              }
              if (type === 1) {
                this.setData({
                  themeItem2: {
                    name: data.name,
                    total: data.total * 100 + '%'
                  }
                })
              }
            }
          }
        }
      });
      chart.render()
      return chart
    })
  },
	// 获取总票房
	getTotalPf(fid) {
		this.setData({
			istotalPfloading: true
		})
		api.getFilmBoxofficeTotal({ fid: fid }).then((res) => {
			this.setData({
				istotalPfloading: false
			})
			if (res.data.length !== 0) {
				var data = res.data[0]
				this.setData({
					totalPfData: data
				})
			} else {
				this.setData({
					totalPfData: []
				})
			}
		})
	},
	// 获取周票房条状图
	getWeekPfChart(data) {
		this.chartComponent = this.selectComponent('#weekpfopts')
		this.chartComponent.init((canvas, width, height) => {
			const chart = new F2.Chart({
				el: canvas,
				width,
				height
			})
			var Global = F2.Global
			chart.source(data, {
				'周总票房': {
					tickCount: 5
				}
			})
			chart.coord({
				transposed: true
			})
			chart.tooltip({
				alwaysShow: true,
				showCrosshairs: true,
				showItemMarker: false,
				onShow: function onShow(ev) {
					var items = ev.items;
					items[0].name = null;
					items[0].value = items[0].value > 999 ? parseFloat(items[0].value / 10000).toFixed(2) + '亿' : items[0].value + '万' 
          items[0].value = '第' + items[0].origin.weekindex + '周  （' +items[0].title + '） ' + items[0].value;
				}
			})
			chart.axis('周名称', {
				line: Global._defaultAxis.line,
				grid: null
			})
			chart.axis('周总票房', {
				line: null,
				grid: Global._defaultAxis.grid,
				label: function label(text, index, total) {
					var textCfg = {};
					if (index === 0) {
						textCfg.textAlign = 'left'
					} else if (index === total - 1) {
						textCfg.textAlign = 'right'
					}
					return textCfg;
				}
			})
			chart.interval().position('周名称*周总票房')
			chart.render()
      var item = {
        '周名称': (data[data.length - 1])['周名称'],
        '周总票房': (data[data.length - 1])['周总票房']
      };
      var point = chart.getPosition(item); 
      chart.showTooltip(point);
			return chart
		})
	},
	// 获取日票房折线图
	getDayPfChart(data) {
		this.chartComponent = this.selectComponent('#daypfopts')
		this.chartComponent.init((canvas, width, height) => {
			const chart = new F2.Chart({
				el: canvas,
				width,
				height
			})

			chart.source(data, {
				'日票房': {
					nice: true
				},
				'票房日期': {
					type: 'timeCat', // 声明该数据的类型
					// formatter: function formatter(val) {
					// 	const value = new Date(val)
					// 	const y = (value.getFullYear() + '').substring(2, 4)
					// 	const m = value.getMonth() < 10 ? '0' + value.getMonth() : value.getMonth()
					// 	const d = value.getDay() < 10 ? '0' + value.getDay() : value.getDay()
					// 	return y + '/' + m + '/' + d
					// },
					tickCount: 4
				},
				weekindex: {
					nice: true
				}
			})
			chart.tooltip({
				alwaysShow: true,
				showCrosshairs: true,
				showItemMarker: false,
				onShow: function onShow(ev) {
					var weekDay = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];		
					var items = ev.items;
					items[0].name = null;
					items[0].value = items[0].value > 999 ? parseFloat(items[0].value / 10000).toFixed(2) + '亿' : items[0].value + '万' 
					var myDate = new Date(Date.parse(items[0].title));
          items[0].value = items[0].title + ' （' + weekDay[myDate.getDay()] + '） ' + items[0].value;
				}
			})
			chart.axis('票房日期', {
				label: function label(text, index, total) {
					var textCfg = {};
					if (index === 0) {
						textCfg.textAlign = 'left';
					} else if (index === total - 1) {
						textCfg.textAlign = 'right';
					}
					return textCfg;
				}
			});
      chart.line().position('票房日期*日票房');
			chart.render()
      var item = {
        '票房日期': (data[0])['票房日期'],
        '日票房': (data[0])['日票房']
      }; 
      var point = chart.getPosition(item); 
      chart.showTooltip(point);
			return chart
		})
	},
	// 获取周票数据
	getWeekPfData(fid) {
		this.setData({
			isWeekPfloading: true
		})
		api.getFilmBoxofficeWeekTotal({ fid: fid }).then((res) => {
			this.setData({
				isWeekPfloading: false
			})
			if (res.data.length !== 0) {
				var data = []
				if (res.data.length > 10) {
					this.setData({
						weekPfboxH: 40 * res.data.length
					})
				}
				for (let i in res.data) {
					data.push({
						'周名称': res.data[i].zmc,
						'周总票房': parseInt(res.data[i].zpf),
						weekindex: parseInt(res.data.length - i)
					})
				}
				this.setData({
					weekPfData: data
				})
				this.getWeekPfChart(data)
			} else {
				this.setData({
					weekPfData: []
				})
			}
			
		})
	},
	// 获取日票数据
	getDayPfData(fid) {
		this.setData({
			isDayPfloading: true
		})
		api.getFilmBoxofficeDailyTotal({ fid: fid}).then((res) => {
			this.setData({
				isDayPfloading: false
			})
			if (res.data.length !== 0) {
				var data = []
				for (let i in res.data) {
					data.push({
						'票房日期': res.data[i].spfrq,
            '日票房': parseFloat(res.data[i].spf)
					})
				}
				this.setData({
					dayPfData: data,
					dateRange: res.dateRange
				})
				this.getDayPfChart(data)
			} else {
				this.setData({
					dayPfData: []
				})
			}
			
		})
	}
})